package org.tamal;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Scanner;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.tamal.spring.Service;

/**
 * This class contains some static methods.
 * @author Tamal Kanti Nath
 */
public final class Util {

    private static ApplicationContext context
        = new ClassPathXmlApplicationContext("spring.xml");

    private Util() {
        // Utility class should not be instantiated.
    }

    /**
     * Returns the service.
     * @return Service
     * @see Service
     */
    public static Service getService() {
        return context.getBean(Service.class);
    }

    /**
     * Reads the input stream and returns a string representation of the input
     * stream.
     * @param inputStream The input stream
     * @return the String read from the input stream
     */
    public static String toString(InputStream inputStream) {
        try (Scanner scanner = new Scanner(inputStream)) {
            return scanner.useDelimiter("\\A").next();
        }
    }

    /**
     * Returns a JSON Object from HTTP GET or POST.
     * @param url The request URL
     * @param data The HTTP post data
     * @return The JSON object
     * @throws IOException exception
     */
    public static String fetchUrl(String url, String data) throws IOException {
        System.setProperty("java.net.useSystemProxies", "true");
        List<Proxy> list;
        try {
            list = ProxySelector.getDefault().select(new URI(url));
        } catch (URISyntaxException e) {
            throw new MalformedURLException(e.getMessage());
        }
        URLConnection conn = null;
        for (Proxy proxy : list) {
            conn = new URL(url).openConnection(proxy);
            break;
        }
        if (conn == null) {
            conn = new URL(url).openConnection();
        }
        if (data != null) {
            conn.setDoOutput(true);
            PrintWriter out = new PrintWriter(conn.getOutputStream());
            out.print(data);
            out.flush();
        }
        return toString(conn.getInputStream());
    }

}
